function TS = readTS(directory, filename)
% TS = readTS(directory, filename) Read a delimited TS from a text file
% and stores the data in a sesame structure.  readTS attempts to determine if the
% first column contains dates.
% Usage:
%    TS = readTS(fullpath)
%    TS = readTS(directory, filename)
% Inputs:
%    fullpath       - Complete file path string
%    directory  - Directory path string
%    filename   - File name string
% Outputs:
%    TS - TS structure with .data, .header and .dates components.
%
% TODO: need to add the ability to read other date formats than YYYYMM(DD)

if nargin == 1; fullpath = char(directory); end
if nargin == 2; fullpath = [char(directory) char(filename)]; end

% Determine filename extension

I = find(fullpath == '.');
if isempty(I)
   ext = '';
else
   ext = fullpath(I(end)+1:end);
end

% Guess delimiters

if strcmp(ext, 'csv')
   delim = ',';
else
   delim = [' ,' sprintf('\t')];
end

% Open file and read first line

fid = fopen(fullpath, 'r');
if fid == -1
   warning(['Unable to open ' fullpath '. Returning fopen error code.'])
   TS = fid;
   return
end
line = fgetl(fid);
% fclose(fid);
if ~ischar(line)
   warning(['End of file encountered unexpectedly in ' fullpath])
end

% Tokenize first line to find number of columns
headers = deblank(strsplit(line, delim));
ncol = length(headers);

% Check if first column is a date column
if strncmpi(headers{1}, 'date', 4)   || strncmpi(headers{1}, 'month', 5)
   TS.header = headers(2:end);
   foundDate = 1;
else
   TS.header = headers;
   foundDate = 0;
end

% Read data
format = repmat('%f' ,1 , ncol);
columns = textscan(fid, format, 'delimiter', delim, 'emptyvalue', NaN);
fclose(fid);

% Finish building sesame structure
if foundDate
   TS.dates = [columns{1}];
   TS.data = [columns{2:end}];
else
   TS.data = [columns{:}];
end

return
